package com.overlord.im.client.netty.handler;

import com.overlord.im.client.api.ClientMsgListener;
import com.overlord.im.client.message.MessageResolverFactory;
import com.overlord.im.client.message.resolver.MessageResolver;
import com.overlord.im.commons.message.OverlordImMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName ImServiceHandler
 * @Author wuwei
 * @Description NONE
 * @Date 2020/5/29 14:33
 **/
@Slf4j
public class ImClientHandler extends SimpleChannelInboundHandler<OverlordImMessage> {

    private ChannelHandlerContext ctx;

    private ClientMsgListener clientMsgListener;

    public ImClientHandler(ClientMsgListener clientMsgListener) {
        this.clientMsgListener = clientMsgListener;
    }

    public void writeAndFlush(OverlordImMessage message) {
        ctx.writeAndFlush(message);
        clientMsgListener.hasSent(message.getClientMessageId());
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        this.ctx = ctx;
        clientMsgListener.online();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, OverlordImMessage overlordImMessage)
            throws Exception {
        log.info("接受到服务端消息:{}", overlordImMessage);
        MessageResolver resolver = MessageResolverFactory.resolver(overlordImMessage);
        if (null != resolver) {
            resolver.resolve(overlordImMessage, channelHandlerContext);
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        clientMsgListener.offline();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        clientMsgListener.hasException(ctx, cause);
    }
}
